package com.fei.fpmall.malladmin.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fei.fpmall.core.utils.Const;
import com.fei.fpmall.core.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fei.fpmall.common.utils.UserUtil;
import com.fei.fpmall.core.annotation.Before;
import com.fei.fpmall.core.annotation.Clear;
import com.fei.fpmall.core.dto.LoginModel;
import com.fei.fpmall.core.dto.ResponseModel;
import com.fei.fpmall.core.utils.FeiConfig;
import com.fei.fpmall.core.utils.StringUtils;
import com.fei.fpmall.entity.basemanage.User;
import com.fei.fpmall.service.basemanage.IUsersService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;


/**
 * @description：账号控制器
 * @author：felix
 * @date：2017年9月12日 下午8:56:58
 */
@Controller
@RequestMapping("/account")
public class AccountController extends BaseController {

    @Resource
    private FeiConfig feiConfig;
    @Autowired
    private Producer producer;
    @Resource
    private IUsersService usersService;

    /**
     * @param model
     * @param redirectUrl
     * @return 登录 get
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @Clear
    public String login(Model model,
                        @RequestParam(value = "redirectUrl", required = false, defaultValue = "") String redirectUrl) {
        User loginMember = UserUtil.getLoginUser(request);
        if (loginMember != null) {
            return "redirect:/";
        }

        Object m = usersService;
        model.addAttribute("redirectUrl", redirectUrl);
        return "account/login";
    }

    /**
     * @param login
     * @param redirectUrl
     * @return
     * @description：登录post
     */
    @Clear()
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(LoginModel login,
                        @RequestParam(value = "redirectUrl", required = false, defaultValue = "") String redirectUrl) {
        ResponseModel<User> responseModel = new ResponseModel<>(2);
        // 验证输入信息
        User LoginUser = null;
        if (feiConfig.getShadowName().equals("username")) {
            if (login.getAccountname() != null && login.getAccountname().length() > 0) {
                // 用户名登录
                Map condition = new HashMap();
                condition.put("username", login.getAccountname());
                LoginUser = usersService.queryObjectByCondition(condition);
            }

        } else if (feiConfig.getShadowName().equals("mobile")) {
            // 手机
            Map condition = new HashMap();
            condition.put("mobile", login.getAccountname());
            LoginUser = usersService.queryObjectByCondition(condition);
        } else {
            // 邮箱
            Map condition = new HashMap();
            condition.put("email", login.getAccountname());
            LoginUser = usersService.queryObjectByCondition(condition);
        }
        if (LoginUser == null) {
            return new ResponseModel(-1, "用户名或密码错误");
        }
        //判断密码是否正确
        if (!Md5Util.getMD5Code(login.getPassword()).equals(LoginUser.getPassword())) {
            //密码校验不通过
            return new ResponseModel(-1, "用户名或密码错误");
        }
        //保存登录信息到session
        UserUtil.setLoginUser(request, LoginUser);

        if (StringUtils.isEmpty(redirectUrl)) {
            redirectUrl = Const.PROJECT_PATH + "/index";
            responseModel.setUrl(redirectUrl);
        }
        return responseModel;
    }

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }

    }
}
